import { login } from '@/api/auth'
import { getUserProfile, updateAvatar, updateBaseInfo } from '@/api/profile'
import { createStore } from 'vuex'

const tokenKey = 'BLOG-TOKEN'
const userInfoKey = 'BLOG-USERINFO'

// 创建状态管理 实例
const store = createStore({
  state: {
    token: localStorage.getItem(tokenKey),
    userInfo: JSON.parse(localStorage.getItem(userInfoKey) || '{}')
  },
  mutations: {
    // 设置Token
    setToken (state, token) {
      state.token = token
      // localStorage本地缓存
      if(state.token) {
        localStorage.setItem(tokenKey, state.token)
      } else {
        localStorage.removeItem(tokenKey)
      }
    },

    // 设置用户资料
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
      if (state.userInfo.username) {
        localStorage.setItem(userInfoKey, JSON.stringify(state.userInfo))
      } else {
        localStorage.removeItem(userInfoKey)
      }
    }
  },
  actions: {
    async login ({ commit }, loginParams) {
      const token = await login(loginParams)
      commit('setToken', token)
    },

    // 请求并设置用户资料
    async getUserInfo ({ commit }) {
      const profile = await getUserProfile()
      console.log(profile)
      commit('setUserInfo', profile)
    },

    // 清除用户的登录信息
    clearLogin ({ commit }) {
      commit('setToken', null)
      commit('setUserInfo', {})
    },

    // 修改个人头像
    async updateProfileAvatar (store, avatar) {
      // 发请求更新到后台
      await updateAvatar(avatar)
      // 更新到vuex中
      store.commit('setUserInfo', {
        ...store.state.userInfo,
        avatar
      })
    },

    // 修改个人基本信息 - 昵称
    async updateProfileBaseInfo (store, data) {
      await updateBaseInfo(data)
      store.commit('setUserInfo', {
        ...store.state.userInfo,
        ...data
      })
    }
  }
})

export default store